package com.zhj.algorithm.search;

/**
 * @PackageName:com.zhj.algorithm.search
 * @ClassName:BinarySearch
 * @auter: 朱慧杰
 * @date:2020/8/8 0008 10:45
 **/
public class BinarySearch {

    // 二分查找
    public int search(int target, int[] arr) {
        int index = -1;
        // 开始位置
        int begin = 0;
        // 结束位置
        int end = arr.length-1;
        // 中间位置
        int mid = (begin+end) / 2;

        while (true) {
            if(begin > end){
                break;
            }
            if (arr[mid] == target) {
                index = mid;
                break;
            } else {
                if (arr[mid] > target) {
                    end = mid - 1;
                } else {
                    begin = mid + 1;
                }
                mid = (begin+end) / 2;
            }
        }

        return index;
    }

}
